<template>
  <div class="component-upload-image">
    <el-upload
      :action="uploadImgUrl"
      list-type="picture-card"
      name="files"
      :file-list="fileList"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :limit="maxCount"
      :headers="headers"
      style="display: inline-block; vertical-align: top"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'MultiUpload',
  props: {
    // 图片属性数组
    value: Array,
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/upload/uploadBatch', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      dialogVisible: false,
      dialogImageUrl: null
    }
  },

  computed: {
    fileList() {
      const fileList = []
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] })
      }
      return fileList
    }
  },
  watch: {},
  methods: {
    emitInput(fileList) {
      const value = []
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url)
      }
      this.$emit('input', value)
    },
    handleBeforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    handleUploadSuccess(res, file) {
      console.log('批量图片', res.data)

      this.fileList.push({ name: file.name, url: res.data[0] })
      this.emitInput(this.fileList)
      // res.data.forEach((item) => {

      // });
      this.loading.close()
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },

    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
      this.loading.close()
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '张图片',
        type: 'warning',
        duration: 1000
      })
    }
  }
}
</script>

<style scoped lang="scss">
.avatar {
  width: 100%;
  height: 100%;
}
</style>
